package com.minimalist.common.feign.fallback.basic;

import com.minimalist.common.entity.basic.vo.file.FileUpdateStatusVO;
import com.minimalist.common.entity.basic.vo.file.FileUploadRespVO;
import com.minimalist.common.entity.basic.vo.file.FileVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.feign.config.BaseFallbackFactory;
import com.minimalist.common.response.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文件管理 Feign 客户端降级工厂
 * 使用FallbackFactory可以获取到异常信息，便于问题排查
 *
 * @author minimalist
 */
@Component
public class FileFeignClientFallbackFactory extends BaseFallbackFactory<FileFeignClient>{
    private static final Logger log = LoggerFactory.getLogger(FileFeignClientFallbackFactory.class);

    @Override
    public FileFeignClient create(Throwable cause){
        return new FileFeignClient(){
            @Override
            public R<FileVO> getFileByFileId(Long fileId){
                logServiceUnavailable("根据文件ID查询文件信息", fileId, cause);
                return R.fail(HttpStatus.SERVICE_UNAVAILABLE.value(), "服务不可用: " + cause.getMessage());
            }

            @Override
            public R<List<FileVO>> getFileListByFileIds(List<Long> fileIds){
                logServiceUnavailable("根据文件ID列表查询文件信息", fileIds, cause);
                return R.fail(HttpStatus.SERVICE_UNAVAILABLE.value(), "服务不可用: " + cause.getMessage());
            }

            @Override
            public R<Void> updateStatusByFileUrl(FileUpdateStatusVO fileUpdateStatusVO){
                logServiceUnavailable("根据文件URL更新文件状态", fileUpdateStatusVO, cause);
                return R.fail(HttpStatus.SERVICE_UNAVAILABLE.value(), "服务不可用: " + cause.getMessage());
            }

            @Override
            public R<FileUploadRespVO> uploadFile(MultipartFile file, Integer fileSource
                    , Long createId, Long updateId, Long tanantId){
                logServiceUnavailable("单文件上传", file != null ? file.getOriginalFilename() : "null", cause);
                return R.fail(HttpStatus.SERVICE_UNAVAILABLE.value(), "服务不可用: " + cause.getMessage());
            }

            @Override
            public R<Void> deleteFile(Long fileId){
                logServiceUnavailable("删除文件", fileId, cause);
                return R.fail(HttpStatus.SERVICE_UNAVAILABLE.value(), "删除文件失败，服务不可用: " + cause.getMessage());
            }

            @Override
            public R<Void> deleteBatchFiles(List<Long> fileIds){
                logServiceUnavailable("批量删除文件", fileIds, cause);
                return R.fail(HttpStatus.SERVICE_UNAVAILABLE.value(), "批量删除文件失败，服务不可用: " + cause.getMessage());
            }
        };
    }
}
